package com.qbw.core.base;

import android.app.Activity;
import android.content.Context;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


/**
 * Created by Bond on 2017/02/08 10:32
 * you can contact me at qbaowei@qq.com
 */


public abstract class BaseHolder<T, B extends ViewDataBinding> extends RecyclerView.ViewHolder {

    protected B mBinding;
    protected Context mContext;
    protected T mData;

    protected Object mListener;

    public BaseHolder(Context context, View itemView) {
        super(itemView);
        mContext = context;
    }

    public BaseHolder(Context context, ViewDataBinding binding) {
        this(context, binding.getRoot());
        mBinding = (B) binding;
    }

    public BaseHolder(Context context, int layoutResId, ViewGroup viewParent) {
        this(context,
             DataBindingUtil.inflate(LayoutInflater.from(context), layoutResId, viewParent, false));
    }

    public BaseHolder(Context context, int layoutResId, ViewGroup viewParent, Object listener) {
        this(context, layoutResId, viewParent);
        mListener = listener;
    }

    public void bindData(int position, T data) {
        mData = data;
    }

    protected boolean finishActivity() {
        if (mContext != null && mContext instanceof Activity) {
            ((Activity) mContext).finish();
            return true;
        }
        return false;
    }

    protected FragmentManager getFragmentManager() {
        if (mListener instanceof BaseFragment) {
            return ((BaseFragment) mListener).getChildFragmentManager();
        } else if (mContext instanceof BaseActivity) {
            return ((BaseActivity) mContext).getSupportFragmentManager();
        }
        return null;
    }

    public B getBinding() {
        return mBinding;
    }

    public boolean isFinishing() {
        if (mContext instanceof Activity) {
            return ((Activity) mContext).isFinishing();
        }
        return false;
    }

    public BaseActivity getActivity() {
        if (mContext instanceof BaseActivity) {
            return (BaseActivity) mContext;
        }
        return null;
    }
}
